﻿Imports System.IO
Imports System.Data.SqlClient

Public Class frmClientNew

    Sub FillClientsAutoList()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select FullName From Clients", cnn)
            Dim Reader As SqlDataReader

            Me.txtClientName.AutoCompleteCustomSource.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Me.txtClientName.AutoCompleteCustomSource.Add(Reader.Item(0))
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub Clear()
        Me.txtClientName.Clear()
        Me.txtTele.Clear()
        Me.txtAddress.Clear()
        Me.txtClientName.Focus()
    End Sub

    Sub CheckRadio()
        If Me.RDirectBusiness.Checked = True Then
            Me.CombProducers.Enabled = False
            Me.RProducer.Checked = False
            Me.CombDirectBusiness.Enabled = True
        ElseIf Me.RProducer.Checked = True Then
            Me.CombDirectBusiness.Enabled = False
            Me.RDirectBusiness.Checked = False
            Me.CombProducers.Enabled = True
        End If
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        Clear()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Me.ErrProv.Clear()
        If Me.txtClientName.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.txtClientName, "Please fill in all mandatory fields")

        ElseIf Me.RDirectBusiness.Checked = True And Me.CombDirectBusiness.SelectedIndex = -1 Then
            Me.ErrProv.SetError(Me.CombDirectBusiness, "Please fill in all mandatory fields")

        ElseIf Me.RProducer.Checked = True And Me.CombProducers.SelectedIndex = -1 Then
            Me.ErrProv.SetError(Me.CombProducers, "Please fill in all mandatory fields")

        Else
            Try
                Me.Cursor = Cursors.WaitCursor

                Dim cmd As New SqlCommand
                Dim Trans As SqlTransaction
                Dim SNo As Integer

                cnn.Open()
                Trans = cnn.BeginTransaction
                cmd.Connection = cnn
                cmd.Transaction = Trans

                Dim Producer As String
                If Me.RDirectBusiness.Checked = True Then
                    Producer = Me.CombDirectBusiness.SelectedItem

                ElseIf Me.RProducer.Checked = True Then
                    Producer = Me.CombProducers.SelectedItem
                End If

                '1) Creat the client profile
                cmd.CommandText = "Insert Into Clients (FullName,Producer,Tele,Address) Values " & _
                                  "(@FullName,@Producer,@Tele,@Address) Select SCOPE_IDENTITY()"

                'Add values
                cmd.Parameters.AddWithValue("@FullName", Me.txtClientName.Text.Trim)
                cmd.Parameters.AddWithValue("@Producer", Producer)
                cmd.Parameters.AddWithValue("@Tele", Me.txtTele.Text.Trim)
                cmd.Parameters.AddWithValue("@Address", Me.txtAddress.Text.Trim)

                SNo = CInt(cmd.ExecuteScalar)

                '2) Save contacts details
                cmd.CommandText = "Insert Into ClientContacts (ClientID,Name,Position,Email,Phone,SavedUser) Values " & _
                                  "(@ClientID,@Name,@Position,@Email,@Phone,@SavedUser) "

                For Each row As DataGridViewRow In Me.GridContactDetails.Rows
                    If row.Index <> Me.GridContactDetails.RowCount - 1 Then
                        cmd.Parameters.Clear()
                        cmd.Parameters.AddWithValue("@ClientID", SNo)
                        cmd.Parameters.AddWithValue("@Name", row.Cells(Me.DGColName.Index).Value)
                        cmd.Parameters.AddWithValue("@Position", row.Cells(Me.DGColPosition.Index).Value)
                        cmd.Parameters.AddWithValue("@Email", row.Cells(Me.DGColEmail.Index).Value)
                        cmd.Parameters.AddWithValue("@Phone", row.Cells(Me.DGColTele.Index).Value)
                        cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                        cmd.ExecuteNonQuery()
                    End If
                Next

                '3) Open an account
                Dim AccNumber As String 'Integer
                Dim AccNo As String

                cmd.CommandText = "Select IsNull(Max(AccNo4),0) From Acc Where Acc1='Assets' and Acc2=N'Current Assets' and Acc3=N'Receivables (Customers)'"
                AccNumber = CInt(cmd.ExecuteScalar) + 1

                'Check if Maximum sub accounts is reached
                If CInt(AccNumber) > 999999999 Then
                    MsgBox("You reached the largest number of clients allowed")
                    Me.btnSave.Enabled = False
                    Exit Sub
                End If

                If AccNumber.ToString.Length < 9 Then
                    For I As Integer = 1 To (9 - AccNumber.Length)
                        AccNumber = "0" + AccNumber
                    Next
                End If

                AccNo = "1103" + AccNumber

                cmd.Parameters.Clear()
                cmd.CommandText = "Insert Into Acc (AccNo,AccNo1,AccNo2,AccNo3,AccNo4,Acc1,Acc2,Acc3,Acc4) Values " & _
                                  "(" & AccNo & ",1,1,3," & AccNumber & ",N'Assets',N'Current Assets',N'Receivables (Customers)',@ClientName)"

                cmd.Parameters.AddWithValue("@ClientName", Me.txtClientName.Text.Trim)
                cmd.ExecuteNonQuery()

                'Update Client
                cmd.CommandText = "Update Clients Set AccNo=N'" & AccNo & "' Where SNo=" & SNo
                cmd.ExecuteNonQuery()

                Trans.Commit()
                cnn.Close()

                Me.txtClientName.AutoCompleteCustomSource.Add(Me.txtClientName.Text.Trim)

                MsgBox("Saved Successfully! " & vbCrLf & "Client ID: " & SNo)

                SelClientID = SNo
                SelClientName = Me.txtClientName.Text.Trim

                Clear()

                'Create directory to store files
                Dim Dir As New DirectoryInfo(FTPAddress + "Clients")
                Dir.CreateSubdirectory("C-" & SNo)

                Me.Cursor = Cursors.Default

                Me.Close()
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Sub FillBranches()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim Branches As ArrayList = GetBranches()

            For Each Branch As String In Branches
                Me.CombDirectBusiness.Items.Add("Direct Business - " & Branch)
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub frmClientsNew_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SelClientID = 0
        SelClientName = ""
        FillClientsAutoList()
        FillProducers()
        FillBranches()

        'Check client profile
        If ClientsProfiles = "Direct Business" OrElse ClientsProfiles = "Retail (FD)" Then
            Me.CombProducers.Text = "Direct Business - " & Branch
        Else
            Me.CombProducers.Text = CurrentUser
        End If
    End Sub

    Sub FillProducers()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim ProducersList As ArrayList = GetProducersList()

            Me.CombProducers.Items.Clear()

            For Each Producer As String In ProducersList
                Me.CombProducers.Items.Add(Producer)
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub RDirectBusiness_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RDirectBusiness.CheckedChanged
        CheckRadio()
    End Sub

    Private Sub RProducer_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RProducer.CheckedChanged
        CheckRadio()
    End Sub

    Private Sub GridContactDetails_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridContactDetails.CellClick
        Try
            If e.ColumnIndex = Me.DGColDelete.Index Then
                Me.GridContactDetails.Rows.RemoveAt(e.RowIndex)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub GridContactDetails_CellEndEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridContactDetails.CellEndEdit
        For Each row As DataGridViewRow In Me.GridContactDetails.Rows
            For i As Integer = 0 To Me.GridContactDetails.Columns.Count - 1
                If row.Cells(i).Value Is Nothing Then
                    row.Cells(i).Value = ""
                End If
            Next
        Next
    End Sub
End Class